package com.jikeh.controller;

import com.jikeh.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.jikeh.service.UserService;

import java.util.List;

/**
 * @author jikeh
 */
@Controller
@RequestMapping("/users")
public class UserController {

	@Autowired
	private UserService userService;

	/**
	 * 显示字典数据列表：http://localhost:8888/mybatis-spring-boot/users?offset=1&limit=2
	 *
	 * @param user
	 * @param offset
	 * @param limit
	 * @return
	 */
	@RequestMapping
	public ModelAndView users(User user, Integer offset, Integer limit) {
		ModelAndView mv = new ModelAndView("user");
		List<User> users = userService.findByUser(user, offset, limit);
		mv.addObject("users", users);
		return mv;
	}

	/**
	 * 新增或修改字典信息页面，使用 get 跳转到页面
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public ModelAndView add(Long id) {
		ModelAndView mv = new ModelAndView("user_add");
		User user;
		if(id == null){
			//如果 id 不存在，就是新增数据，创建一个空对象即可
			user = new User();
			mv.addObject("usermsg", "添加用户");
		} else {
			//如果 id 存在，就是修改数据，把原有的数据查询出来
			user = userService.findById(id);
			mv.addObject("usermsg", "修改用户");
		}
		mv.addObject("model", user);
		return mv;
	}

	/**
	 * 新增或修改字典信息，通过表单 post 提交数据
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "add", method = RequestMethod.POST)
	public ModelAndView save(User user) {
		ModelAndView mv = new ModelAndView();
		try {
			userService.saveOrUpdate(user);
			mv.setViewName("redirect:/users");
		} catch (Exception e){
			mv.setViewName("user_add");
			mv.addObject("msg", e.getMessage());
			mv.addObject("model", user);
		}
		return mv;
	}

	/**
	 * 通过 id 删除字典信息
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap delete(@RequestParam Long id) {
		ModelMap modelMap = new ModelMap();
		try {
			boolean success = userService.deleteById(id);
			modelMap.put("success", success);
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("msg", e.getMessage());
		}
		return modelMap;
	}

}
